/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rbh.risk.dao.impl;

import com.rbh.risk.dao.DrugItemsDao;
import com.rbh.risk.entity.DrugItems;
import com.rbh.risk.support.SessionFactorySupport;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

@Repository("drugItemsDao")
public class DrugItemsDaoImpl extends SessionFactorySupport implements DrugItemsDao {

    @Override
    public DrugItems getById(String icode) throws DataAccessException {
        DrugItems result = null;
        try {
            result = (DrugItems) super.getSessionFactory().getCurrentSession().get(DrugItems.class, icode);
        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }

    @Override
    public List<DrugItems> getAll() throws DataAccessException {
        List<DrugItems> results = null;
        try {
            Query query = super.getSessionFactory().getCurrentSession().createQuery("from " + DrugItems.class.getName());
            results = query.list();
        } catch (Exception ex) {
            throw ex;
        }
        return results;
    }

    @Override
    public List<DrugItems> getByWords(String words) throws DataAccessException {
        List<DrugItems> results = null;
        try {
            String filter = words.trim();
            if (filter.isEmpty() || filter == null) {
                return null;
            } else {
                Criteria criteria = super.getSessionFactory().getCurrentSession().createCriteria(DrugItems.class);
                criteria.add(Restrictions.conjunction()
                        .add(Restrictions.le("accessLevel", 0))
                        .add(Restrictions.eq("istatus", 'Y'))
                        .add(Restrictions.disjunction()
                        .add(Restrictions.like("name", filter, MatchMode.ANYWHERE))
                        .add(Restrictions.like("drugnote", filter, MatchMode.ANYWHERE))));
                criteria.addOrder(Order.asc("name"));
                criteria.setMaxResults(50);
                results = criteria.setCacheable(true).list();
            }
        } catch (Exception ex) {
            throw ex;
        }
        return results;
    }
}
